import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useLcpStore = defineStore('lcpImage', () => {
  // 默认LCP图片URL
  const lcpImageUrl = ref('https://melov-net.oss-us-west-1.aliyuncs.com/upload/20250314161015/20250314161015_67d3e4674a10c.jpg')
  
  // 预加载LCP图片并更新状态
  const preloadLcpImage = (imageUrl: string) => {
    if (!imageUrl) return;
    
    // 创建预加载链接
    const linkEl = document.createElement('link')
    linkEl.rel = 'preload'
    linkEl.href = imageUrl
    linkEl.as = 'image'
    linkEl.fetchPriority = 'high'
    document.head.appendChild(linkEl)
    
    // 更新状态
    lcpImageUrl.value = imageUrl
  }
  
  // 检查图片是否已加载
  const isImagePreloaded = (imageUrl: string): boolean => {
    const links = document.querySelectorAll('link[rel="preload"]')
    for (let i = 0; i < links.length; i++) {
      if (links[i].getAttribute('href') === imageUrl) {
        return true
      }
    }
    return false
  }

  return {
    lcpImageUrl,
    preloadLcpImage,
    isImagePreloaded
  }
}, {
  persist: false // 不需要持久化，每次加载页面时都会重新获取
})

// 导出到index.ts
export * from './lcpImage' 